import csv
import os
from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render
from django.core.paginator import Paginator
from django.views import View
from django.conf import settings
from .models import DatasetInfo

# Create dataset views here.

# 展示数据集
def display(request):
    dataset_list = DatasetInfo.objects.all()
    paginator = Paginator(dataset_list, 12)  # Show 12 datasets per page.
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {
        'page_obj': page_obj,
        'total_dataset_count': paginator.count,
    }
    return render(request, 'dataset/dataset-display.html', context=context)


# 添加数据集视图类
class UploadView(View):
    def get(self, request):
        return render(request, 'dataset/dataset-upload.html')

    def post(self, request):
        file = request.FILES.get('file-input')
        if file:
            # 读取CSV文件内容
            if file.name.endswith('.csv'):
                file_path = os.path.join(settings.MEDIA_ROOT, 'datasets', file.name)
                with open(file_path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)

                # 打开文件，逐行读取
                with open(file_path, newline='', encoding='utf-8') as csvfile:
                    reader = csv.reader(csvfile)
                    next(reader)  # 跳过第一行标题
                    for row in reader:
                        # 使用DatasetInfo模型的字段顺序创建对象
                        DatasetInfo.objects.create(
                            province=row[0],
                            city=row[1],
                            time=datetime.strptime(row[2], '%Y-%m-%d'),
                            aqi=row[3] if row[3] else 0,
                            pm2_5=row[4] if row[4] else 0,
                            pm10=row[5] if row[5] else 0,
                            so2=row[6] if row[6] else 0,
                            no2=row[7] if row[7] else 0,
                            co=row[8] if row[8] else 0,
                            o3=row[9] if row[9] else 0,
                            complexindex=row[10] if row[10] else 0,
                            rank=row[11] if row[11] else 0,
                            primary_pollutant=row[12],
                            temp=row[13] if row[13] else 0,
                            humi=row[14] if row[14] else 0,
                            windlevel=row[15] if row[15] else 0,
                            winddirection=row[16],
                            weather=row[17]
                        )
                return render(request, 'dataset/dataset-upload.html', {'message': '上传并处理成功!'})
            else:
                return render(request, 'dataset/dataset-upload.html', {'message': '请上传CSV格式的文件!'})
        else:
            return render(request, 'dataset/dataset-upload.html', {'message': '上传失败，请选择文件!'})
